<template>
  <view class="container">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-section">
      <van-loading size="24px" />
      <text class="loading-text">正在加载订单信息...</text>
    </view>

    <view v-else>
      <!-- 订单信息 -->
      <view class="order-info" v-if="orderDetail">
        <van-cell-group>
          <van-cell title="订单信息" :border="false" />
          <van-cell title="订单号" :value="orderDetail.orderNo" />
          <van-cell title="订单状态" :value="orderDetail.status === 0 ? '未支付' : '已支付'" />
          <van-cell title="订单金额" :value="`￥${orderDetail.amount}`" />
        </van-cell-group>
      </view>

      <!-- 预约信息确认 -->
      <view class="appointment-info">
        <van-cell-group>
          <van-cell title="预约信息" :border="false" />
          <van-cell title="科室" :value="departmentName" />
          <van-cell title="医生" :value="doctorName" />
          <van-cell title="日期" :value="date" />
          <van-cell title="时间" :value="time" />
          <van-cell title="挂号费" :value="`￥${fee}`" />
        </van-cell-group>
      </view>



      <!-- 支付方式 -->
      <view class="payment-method">
        <van-cell-group>
          <van-cell title="支付方式" :border="false" />
          <van-radio-group v-model="selectedPayment">
            <van-cell title="微信支付" clickable @click="selectedPayment = 'wechat'">
              <template #right-icon>
                <van-radio name="wechat" />
              </template>
            </van-cell>
            <van-cell title="支付宝" clickable @click="selectedPayment = 'alipay'">
              <template #right-icon>
                <van-radio name="alipay" />
              </template>
            </van-cell>
          </van-radio-group>
        </van-cell-group>
      </view>

      <!-- 底部支付按钮 -->
      <view class="bottom-action">
        <van-submit-bar
          :price="fee * 100"
          button-text="立即支付"
          @submit="handlePayment"
        />
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { getOrder, payOrder, type OrderDetail, type PayOrderRequest } from "@/api/order";
import { useMedicalStore } from '@/stores/modules/medical';

// Store实例
const medicalStore = useMedicalStore();

// 订单相关
const orderId = ref("");
const orderDetail = ref<OrderDetail | null>(null);
const loading = ref(false);

// 预约信息
const doctorId = ref("");
const doctorName = ref("");
const departmentName = ref("");
const date = ref("");
const time = ref("");
const fee = ref(0);

const selectedPayment = ref("wechat");

const patientInfo = reactive({
  name: "",
  phone: "",
  idCard: "",
  gender: "male"
});

// 获取订单详情
const fetchOrderDetail = async () => {
  if (!orderId.value) {
    console.warn('没有订单ID，跳过查询订单');
    return;
  }

  loading.value = true;
  try {
    console.log('查询订单详情，orderId:', orderId.value);
    
    const response = await getOrder(orderId.value, 0);
    
    console.log('订单详情API响应:', response);
    
    if (response.code === 200 && response.data) {
      orderDetail.value = response.data;
      
      // 用后端返回的金额覆盖前端传参
      if (typeof response.data.amount === 'number') {
        fee.value = response.data.amount;
        console.log('更新费用为:', response.data.amount);
      }
      
      console.log('订单详情设置成功:', orderDetail.value);
    } else {
      console.error('获取订单详情失败:', response);
      uni.showToast({ 
        title: response.msg || '获取订单详情失败', 
        icon: 'none' 
      });
    }
  } catch (error) {
    console.error('查询订单详情异常:', error);
    uni.showToast({ 
      title: '网络错误，请重试', 
      icon: 'none' 
    });
  } finally {
    loading.value = false;
  }
};

// const validateForm = () => {
//   if (!patientInfo.name) {
//     uni.showToast({ title: "请输入患者姓名", icon: "none" });
//     return false;
//   }
//   if (!patientInfo.phone) {
//     uni.showToast({ title: "请输入手机号", icon: "none" });
//     return false;
//   }
//   if (!/^1[3-9]\d{9}$/.test(patientInfo.phone)) {
//     uni.showToast({ title: "手机号格式错误", icon: "none" });
//     return false;
//   }
//   if (!patientInfo.idCard) {
//     uni.showToast({ title: "请输入身份证号", icon: "none" });
//     return false;
//   }
//   return true;
// };

const handlePayment = async () => {
  if (!orderDetail.value) {
    uni.showToast({ title: "订单信息不完整", icon: "none" });
    return;
  }

  try {
    uni.showLoading({ title: "支付中..." });

    // 从 store 或其他地方获取必要参数
    const currentAppointment = medicalStore.getCurrentAppointment();
    
    const payParams: PayOrderRequest = {
      id: orderDetail.value.id,
      patientId: 1, // 可以从 medicalStore 或 URL 参数获取
      staffId: currentAppointment?.doctorId ? parseInt(currentAppointment.doctorId) : parseInt(doctorId.value) || 2001,
      typeId: 1, // 线下预约固定为1
      amount: orderDetail.value.amount,
      payDeadline: orderDetail.value.payDeadline,
      userId: parseInt(orderDetail.value.userId) || 2
    };

    console.log('发起支付请求:', payParams);

    const response = await payOrder(payParams);
    
    console.log('支付响应:', response);

    uni.hideLoading();

    if (response.code === 200) {
      // 支付成功
      uni.showModal({
        title: "支付成功",
        content: "预约挂号成功，请按时就诊",
        showCancel: false,
        success: () => {
          // 返回到首页或预约记录页面
          uni.navigateBack({ delta: 4 });
        }
      });
    } else {
      uni.showToast({
        title: response.msg || "支付失败，请重试",
        icon: "none"
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('支付异常:', error);
    uni.showToast({
      title: "支付失败，请重试",
      icon: "none"
    });
  }
};

onLoad(async (options: any) => {
  console.log("支付页面 onLoad", options);
  
  // 优先使用 orderId，如果没有则使用 orderNo
  orderId.value = options.orderId || options.orderNo || "";
  
  doctorId.value = options.doctorId || "";
  doctorName.value = options.doctorName || "";
  departmentName.value = options.departmentName || "";
  date.value = options.date || "";
  time.value = options.time || "";
  fee.value = Number(options.fee) || 0;
  
  // 查询订单详情
  await fetchOrderDetail();
});
</script>

<style lang="scss">
.container {
  background-color: #f8f9fa;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.loading-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  gap: 16rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #969799;
}

.order-info,
.appointment-info,
.patient-info,
.payment-method {
  background: white;
  margin-bottom: 16rpx;
}

.bottom-action {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100;
}
</style>